import { defineStore } from "pinia";
import { UserState } from "@/store/modules/user/types";
import { UserInfo } from "@/types/user";
import { closeSocket, initSocket } from "@/utils/websocket";

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    user: {},
  }),
  getters: {
    isLogin(state: UserState): boolean {
      return !!state.user.id;
    },
  },
  actions: {
    // 设置用户信息
    setUser(value?: UserInfo) {
      this.user = { ...this.user, ...(value || {}) };
    },
    // 清空用户信息
    clearUserState() {
      this.user = {};
      localStorage.removeItem("token");
      // closeSocket();
    },
    // 登陆成功
    loginSuccess(user: UserInfo, token: string) {
      this.setUser(user);
      localStorage.setItem("token", token);
      // initSocket(token);
    },
  },
});
